package Im;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.List;

public class Zhongisheng extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JTextField StudentId;
    private JTextField Name;
    private JTextField Age;
    private JEditorPane editorPane;
    private List<String> studentData = new ArrayList<>();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                Zhongisheng frame = new Zhongisheng();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * Create the frame.
     */
    public Zhongisheng() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 650, 400);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        JLabel lblNewLabel = new JLabel("学号：");
        lblNewLabel.setBounds(10, 11, 54, 15);
        contentPane.add(lblNewLabel);
        
        JLabel lblNewLabel_1 = new JLabel("姓名：");
        lblNewLabel_1.setBounds(10, 46, 54, 15);
        contentPane.add(lblNewLabel_1);
        
        JLabel lblNewLabel_2 = new JLabel("年龄：");
        lblNewLabel_2.setBounds(10, 81, 54, 15);
        contentPane.add(lblNewLabel_2);
        
        StudentId = new JTextField();
        StudentId.setBounds(67, 8, 95, 21);
        contentPane.add(StudentId);
        StudentId.setColumns(10);
        
        Name = new JTextField();
        Name.setBounds(67, 43, 95, 21);
        contentPane.add(Name);
        Name.setColumns(10);
        
        Age = new JTextField();
        Age.setBounds(67, 78, 95, 21);
        contentPane.add(Age);
        Age.setColumns(10);
        
        JButton saveButton = new JButton("保存");
        saveButton.setBounds(10, 130, 89, 25);
        contentPane.add(saveButton);
        saveButton.addActionListener(this::saveData);
        
        JButton showButton = new JButton("显示");
        showButton.setBounds(109, 130, 89, 25);
        contentPane.add(showButton);
        showButton.addActionListener(this::showData);
        
        JButton updateButton = new JButton("更新");
        updateButton.setBounds(208, 130, 89, 25);
        contentPane.add(updateButton);
        updateButton.addActionListener(this::updateData);
        
        JButton clearButton = new JButton("清空数据");
        clearButton.setBounds(307, 130, 89, 25);
        contentPane.add(clearButton);
        clearButton.addActionListener(this::clearData);
        
        editorPane = new JEditorPane();
        editorPane.setBounds(10, 180, 626, 170);
        contentPane.add(editorPane);
        
        // Load existing data
        loadStudentData();
    }

    private void saveData(ActionEvent event) {
        String studentId = StudentId.getText().trim();
        if (studentId.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入学号", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (isStudentIdExists(studentId)) {
            JOptionPane.showMessageDialog(this, "添加重复学号失败", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("students.txt", true))) {
            writer.write(studentId + "," + Name.getText().trim() + "," + Age.getText().trim() + "\n");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "保存数据时出错！", "错误", JOptionPane.ERROR_MESSAGE);
        }
        loadStudentData(); // Reload data to show the new entry
    }
    
    private boolean isStudentIdExists(String studentId) {
        for (String line : studentData) {
            String[] parts = line.split(",", 3); // Split only on the first comma
            if (parts.length > 0 && parts[0].trim().equals(studentId)) {
                return true;
            }
        }
        return false;
    }
    
    private void showData(ActionEvent event) {
        loadStudentData(); // Ensure data is loaded before showing
        StringBuilder data = new StringBuilder();
        for (String line : studentData) {
            data.append(line).append("\n");
        }
        editorPane.setText(data.toString());
    }
    
    private void updateData(ActionEvent event) {
        String studentId = StudentId.getText().trim();
        if (studentId.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入学号", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }
        boolean updated = false;
        List<String> updatedData = new ArrayList<>();
        for (String line : studentData) {
            String[] parts = line.split(",", 3); // Split only on the first comma
            if (parts.length > 0 && parts[0].trim().equals(studentId)) {
                updatedData.add(studentId + "," + Name.getText().trim() + "," + Age.getText().trim());
                updated = true;
            } else {
                updatedData.add(line);
            }
        }
        if (updated) {
            try (BufferedWriter writer = new BufferedWriter(new FileWriter("students.txt"))) {
                for (String line : updatedData) {
                    writer.write(line);
                    writer.newLine();
                }
                JOptionPane.showMessageDialog(this, "数据更新成功！");
                loadStudentData(); // Reload data to show the updated entry
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "更新数据时出错！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "未找到匹配的学号", "警告", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void clearData(ActionEvent event) {
        int result = JOptionPane.showConfirmDialog(this, "确定要清空所有数据吗？", "清空数据", JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter("students.txt"));
                writer.write("");
                writer.close();
                StudentId.setText("");
                Name.setText("");
                Age.setText("");
                editorPane.setText("");
                studentData.clear();
                JOptionPane.showMessageDialog(this, "所有数据已清空！");
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "清空数据时出错！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void loadStudentData() {
        studentData.clear();
        try (BufferedReader reader = new BufferedReader(new FileReader("students.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                studentData.add(line);
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "读取数据时出错！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}